import xmpp

import app_settings

_connection = None

def get_connection(cl):
    global _connection

    if not _connection:
        _connection = cl.connect(
                server=(
                    app_settings.MICROBLOG_GTALK_HOST,
                    app_settings.MICROBLOG_GTALK_PORT
                    )
                )

    return _connection

def send(entry):
    cl = xmpp.Client(app_settings.MICROBLOG_GTALK_CLIENT)

    # Get connection
    con = get_connection(cl)

    if not con:
        if __debug__:
            raise AssertationError("Can't connect to host")
        return 

    # Authenticates
    auth = cl.auth(
            app_settings.MICROBLOG_GTALK_ID,
            app_settings.MICROBLOG_GTALK_PASSWORD,
            )

    if not auth:
        if __debug__:
            raise AssertationError("Can't authenticate")
        return 

    # Propagate presence
    cl.sendInitPresence(requestRoster=0)

    sent_messages = 0

    # Send messages to users
    for mup in entry.get_gtalk_recipients():
        msg = cl.send(xmpp.protocol.Message(mup.gtalk_id, entry.content))
        sent_messages += 1

    return sent_messages

